package com.myslef.teaching_platfrom.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.myslef.teaching_platfrom.common.R;
import com.myslef.teaching_platfrom.common.WebSocketServer;
import com.myslef.teaching_platfrom.domain.Message;
import com.myslef.teaching_platfrom.domain.users.User;
import com.myslef.teaching_platfrom.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private WebSocketServer webSocketServer;

    @PostMapping("/send")
    public R sendMessage(@RequestBody Map map){
        Integer formId = (Integer) map.get("fromId");
        Integer toId = (Integer) map.get("toId");
        String content = (String) map.get("content");
        Message message = new Message();
        message.setFromId(formId);
        message.setToId(toId);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        message.setCreateTime(timestamp);
        message.setContent(content);
        boolean save = messageService.save(message);
        //将信息转换为json格式发送给前端
        if(formId != toId){
            System.out.println("formId");
            map.put("createTime:", timestamp);
            JSONObject json = new JSONObject(map);
            webSocketServer.sendOneMessage(toId, json.toJSONString());
        }
        if(!save)
            return R.error("发送失败");
        return R.success("发送成功！");
    }

    @GetMapping("/getMessages/{from_id}/{to_id}")
    public R getMessageList(@PathVariable("from_id") Integer from_id, @PathVariable("to_id") Integer to_id){
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        List<Message> messageList = messageService.getMessageListById(from_id, to_id);
        return R.success(messageList);
    }

    @GetMapping("/getUsers/{id}")
    public R getUserList(@PathVariable Integer id){
        List<User> userListById = messageService.getUserListById(id);
        return R.success(userListById);
    }

}
